package cn.larry.demo.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import cn.larry.demo.domain.Person;


/**
 * 针对Person类的校验器。
 * 
 * @author LarryZeal
 *
 */
public class PersonValidator implements Validator {
	private final int MINIMUM_NAME_LENGTH = 3; // 最小name长度

	@Override
	public boolean supports(Class<?> clazz) {
		return Person.class.equals(clazz); // 仅支持Person的验证
	}

	/**
	 * 这里只校验了name长度，不能小于3。仅作示例。
	 */
	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required");
		Person person = (Person) target;
		if (person.getName() != null && person.getName().trim().length() < MINIMUM_NAME_LENGTH) {
			errors.rejectValue(
					"name", "field.min.length",
					new Object[] { Integer.valueOf(MINIMUM_NAME_LENGTH) },
					"The password must be at least [" + MINIMUM_NAME_LENGTH + "] characters in length.");
		}

	}

}
